package com.xy.sqldoc.service;

import com.xy.sqldoc.enums.ExportType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class MarkdownExportService extends AbstractExportService {

    @Override
    public void export(String databaseName,
                       List<Map<String, Object>> tables,
                       Map<String, List<Map<String, Object>>> tableColumnsMap,
                       String fileName) {

        StringBuilder markdownBuilder = new StringBuilder();

        // 添加文档标题
        markdownBuilder.append("# ").append(databaseName).append(" 数据库设计文档")
                .append("\n\n");

        // 生成表目录
        markdownBuilder.append("## 数据库表目录")
                .append("\n\n");

        // 创建表格头部
        markdownBuilder.append("| 序号 | 表名 | 注释/说明 |\n")
                .append("|------|------|-----------|\n");

        // 添加表目录内容
        for (int i = 0; i < tables.size(); i++) {
            Map<String, Object> table = tables.get(i);
            String tableName = (String) table.get("table_name");
            String tableComment = Objects.toString(table.get("table_comment"), "");

            markdownBuilder.append("| ")
                    .append(i + 1)
                    .append(" | ")
                    .append(tableName)
                    .append(" | ")
                    .append(tableComment)
                    .append(" |\n");
        }

        markdownBuilder.append("\n\n");

        // 生成表结构详细信息
        markdownBuilder.append("## 数据库表结构")
                .append("\n\n");

        for (Map<String, Object> table : tables) {
            String tableName = (String) table.get("table_name");
            String tableComment = Objects.toString(table.get("table_comment"), "");

            // 添加表名
            markdownBuilder.append("### ").append(tableName).append(" (").append(tableComment).append(")")
                    .append("\n\n");

            // 创建表结构表格头部
            markdownBuilder.append("| 序号 | 列名 | 数据类型 | 长度 | 主键 | 自增 | 允许空 | 默认值 | 列说明 |\n")
                    .append("|------|------|----------|------|------|------|--------|--------|--------|\n");

            // 查询表字段信息
            List<Map<String, Object>> columns = tableColumnsMap.get(tableName);

            for (int i = 0; i < columns.size(); i++) {
                Map<String, Object> column = columns.get(i);
                String columnName = (String) column.get("column_name");
                String dataType = (String) column.get("data_type");
                Integer characterMaximumLength = (Integer) column.get("character_maximum_length");
                String columnKey = Objects.toString(column.get("column_key"), "");
                String isAutoIncrement = Objects.toString(column.get("is_auto_increment"), "");
                String isNullable = Objects.toString(column.get("is_nullable"), "");
                String columnDefault = Objects.toString(column.get("column_default"), "");
                String columnComment = Objects.toString(column.get("column_comment"), "");

                markdownBuilder.append("| ")
                        .append(i + 1)
                        .append(" | ")
                        .append(columnName)
                        .append(" | ")
                        .append(dataType)
                        .append(" | ")
                        .append(characterMaximumLength != null ? characterMaximumLength : "")
                        .append(" | ")
                        .append("PRI".equals(columnKey) ? "√" : "")
                        .append(" | ")
                        .append("YES".equals(isAutoIncrement) ? "√" : "")
                        .append(" | ")
                        .append("YES".equals(isNullable) ? "√" : "")
                        .append(" | ")
                        .append(columnDefault)
                        .append(" | ")
                        .append(columnComment)
                        .append(" |\n");
            }

            markdownBuilder.append("\n\n");
        }

        // 写入Markdown文件
        try (FileWriter writer = new FileWriter(outputPath + fileName)) {
            writer.write(markdownBuilder.toString());
            log.info("Markdown数据库文档生成成功，输出路径：{}", outputPath);
        } catch (IOException e) {
            log.error("写入Markdown数据库文档失败", e);
        }

    }

    @Override
    public ExportType getExportType() {
        return ExportType.MD;
    }
}
